const { executeQuery } = require('../config/db_config')
const express = require('express')
require("dotenv/config")
const {
  ApiError,
  CheckoutPaymentIntent,
  Client,
  Environment,
  LogLevel,
  OrdersController,
} = require("@paypal/paypal-server-sdk");
const { escape } = require('mysql')
let orderRouter = express.Router()
orderRouter.use(express.json())


const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET } = process.env;

const client = new Client({
  clientCredentialsAuthCredentials: {
    oAuthClientId: PAYPAL_CLIENT_ID,
    oAuthClientSecret: PAYPAL_CLIENT_SECRET,
  },
  timeout: 0,
  environment: Environment.Sandbox,
  logging: {
    logLevel: LogLevel.Info,
    logRequest: {
      logBody: true,
    },
    logResponse: {
      logHeaders: true,
    },
  },
});

const ordersController = new OrdersController(client);


/**
 * 创建一个订单，开始交易
 * @param {} cart 
 * @returns 
 */
const createOrder = async (cart) => {
  const collect = {
    body: {
      intent: CheckoutPaymentIntent.Capture,
      purchaseUnits: [
        {
          amount: cart
        },
      ],
    },
    prefer: "return=minimal",
  };

  try {
    const { body, ...httpResponse } = await ordersController.createOrder(
      collect
    );
    // Get more response info...
    // const { statusCode, headers } = httpResponse;
    return {
      jsonResponse: JSON.parse(body),
      httpStatusCode: httpResponse.statusCode,
    };
  } catch (error) {
    if (error instanceof ApiError) {
      // const { statusCode, headers } = error;
      throw new Error(error.message);
    }
  }
};

/**
 * 捕获创建的订单以完成交易
 * @param {*} orderID 
 * @returns 
 */
const captureOrder = async (orderID) => {
  const collect = {
    id: orderID,
    prefer: "return=minimal",
  };

  try {
    const { body, ...httpResponse } = await ordersController.captureOrder(
      collect
    );
    return {
      jsonResponse: JSON.parse(body),
      httpStatusCode: httpResponse.statusCode,
    };
  } catch (error) {
    if (error instanceof ApiError) {
      throw new Error(error.message);
    }
  }
};


/**
 * 创建订单
 */
orderRouter.post("/api/orders", async (req, res) => {
  console.log("aaaaa");
  
  try {
    const data = req.body.data.data;
    const coupon_id = req.body.data.coupon_id
    let sum = 0
    data.forEach(k=>{
      sum += k.price*k.num
    })
    if(coupon_id){
      let sql = `select count(*) as num from coupon_user where user_id=${data[0].user_id} and coupon_id=${coupon_id}`
      let res = await executeQuery(sql)
      if(res[0]?.num==0){
        res.status(5000).json({ error: "not have enough coupon" })
        return 
      }
      if(res[0]?.num==1){
        sql = `delete from  coupon_user where user_id=${data[0].user_id} and coupon_id=${coupon_id}`
      }else{
        sql = `update coupon_user set num=num-1 where user_id=${data[0].user_id} and coupon_id=${coupon_id}`
      }
      await executeQuery(sql)
      sql = `select coupons.discount_value as count from coupons where id=${coupon_id}`
      res = await executeQuery(sql)
      sum = sum*res[0]?.count
    }
    
    const cart = {
      currencyCode:'USD',
      value:sum.toString()
    }
    
    const {jsonResponse,httpStatusCode} = await createOrder(cart);
    
    let data1 = data.map(k=>{
      return {
        id:jsonResponse.id,
        user_id:k.user_id,
        good_id:k.good_id,
        price:k.price,
        num:k.num,
        price:k.price,
        time:k.time,
        status:jsonResponse.status
      }
    })
    let sql = 'insert into `order` values'
    data1.forEach((k,v)=>{
      if(v==data1.length-1){
        sql += `('${k.id}',${k.user_id},${k.good_id},${k.num},${k.price},'${k.time}','${k.status}',${coupon_id?coupon_id:-1})`
      }else{
        sql += `('${k.id}',${k.user_id},${k.good_id},${k.num},${k.price},'${k.time}','${k.status}',,${coupon_id?coupon_id:-1}),`
      }
      
    })
    await executeQuery(sql)
    console.log(jsonResponse);
    
    res.status(httpStatusCode).json(jsonResponse);
  } catch (error) {
    console.error("Failed to create order:", error);
    res.status(500).json({ error: "Failed to create order." });
  }
});

/**
 * 为订单捕获支付
 */
orderRouter.post("/api/orders/:orderID/capture", async (req, res) => {
  try {
    const { orderID } = req.params;
    const { jsonResponse, httpStatusCode } = await captureOrder(orderID);
    const sql = 'update `order` set status = "'+jsonResponse.status+'" where id="'+orderID+'"'
    await executeQuery(sql)
    res.status(httpStatusCode).json(jsonResponse);
  } catch (error) {
    console.error("Failed to create order:", error);
    res.status(500).json({ error: "Failed to capture order." });
  }
});

/**
 * 获取指定用户前5条订单数据
 */
orderRouter.get("/history",async(req,resp)=>{
  const id = req.query.id
  const sql = 'select `order`.*,goods.img,goods.title from `order`,goods where `order`.good_id=goods.id and user_id='+id +' limit 5'
  const res = await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
    data:res
  })
})
/**
 * 获取所有用户的订单数据
 */
orderRouter.get("/list",async(req,resp)=>{
  const limit = req.query.limit
  const startIndex = (req.query.now_page-1)*limit
  const sql = 'select `order`.*,goods.img,goods.title,user.username from `order`,goods,user where `order`.good_id=goods.id and `order`.user_id = user.id limit '+startIndex+','+limit
  const sql1 = 'select count(*) as total from `order`,goods where `order`.good_id=goods.id'
  const res = await executeQuery(sql)
  const res1 = await executeQuery(sql1)
  resp.send({
    code:200,
    msg:'success',
    data:{
      list:res,
      total:res1[0].total
    }
  })
})

/**
 * 删除指定订单
 */
orderRouter.delete("/",async(req,resp)=>{
  const id = req.query.id
  const user_id = req.query.user_id
  const good_id = req.query.good_id
  const sql = 'delete  from `order` where `order`.id="'+id+'" and user_id='+user_id+' and good_id='+good_id
 await executeQuery(sql)
  resp.send({
    code:200,
    msg:'success',
  })
})

// 分页查询订单
orderRouter.post('/', async (req, resp) => {
    try {
        console.log(req.body)
        const { 
            page = 1, 
            pageSize = 10, 
            userId
        } = req.body;

        if (!userId) {
            return resp.status(400).send({
                code: 400,
                message: '用户ID不能为空'
            });
        }

        // 计算分页参数
        const offset = (page - 1) * pageSize;

        // 查询订单列表
        const listSql = `
            SELECT 
                o.*,
                g.img as good_img,
                g.title as good_title,
                u.username
            FROM \`order\` o
            LEFT JOIN goods g ON o.good_id = g.id
            LEFT JOIN user u ON o.user_id = u.id
            WHERE o.user_id = ${escape(userId)}
            ORDER BY o.time DESC
            LIMIT ${offset}, ${pageSize}
        `;

        // 查询总记录数
        const countSql = `
            SELECT COUNT(*) as total
            FROM \`order\` o
            WHERE o.user_id = ${escape(userId)}
        `;

        const [orders, countResult] = await Promise.all([
            executeQuery(listSql),
            executeQuery(countSql)
        ]);

        resp.send({
            code: 200,
            message: 'success',
            data: {
                list: orders,
                total: countResult[0].total,
                page: parseInt(page),
                pageSize: parseInt(pageSize)
            }
        });
    } catch (error) {
        console.error('查询订单失败:', error);
        resp.status(500).send({
            code: 500,
            message: '查询订单失败'
        });
    }
});

module.exports = {
  orderRouter
}